package com.study.suanfa.paixu;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @description: xier   希尔排序
 * @date: 2020/12/2 9:48
 * @author: hcm
 * @version: 1.0
 */
public class xier {
    public static void main(String[] args) {
        int[] arr = RandomArr.randomArray(0, 80000, 80000);
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d1 = simpleDateFormat.format(date1);
        System.out.println("排序前：" + d1);
        //shellShort(arr);
        shellShort2(arr);
        Date date2 = new Date();
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d2 = simpleDateFormat2.format(date2);
        System.out.println("排序后：" + d2);
    }

    /**
     * 移位法
     *
     * @param arr
     */
    private static void shellShort2(int[] arr) {
        for (int gap = 2; gap >= 1; gap = gap / 2) {
            //此循环让j往下走
            for (int i = gap; i < arr.length; i++) {
                int j = i;
                int temp = arr[j];
                if(arr[j]<arr[j-gap]){
                    while (j-gap>=0&&temp<arr[j-gap]){
                        arr[j] = arr[j-gap];
                        j-= gap;
                    }
                    arr[j] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 希尔排序，增量排序法
     *
     * @param arr
     */
    public static void shellShort(int[] arr) {
        //此循环设置增量
        for (int gap = 2; gap >= 1; gap = gap / 2) {
            //此循环让j往下走
            for (int i = gap; i < arr.length; i++) {
                //j=j-map，分成了gap组,每组元素要比较
                for (int j = i - gap; j >= 0; j -= gap) {


                    //交换位置
                    if (arr[j] > arr[j + gap]) {
                        int temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }
        }
        System.out.println(Arrays.toString(arr));

    }
}
